
import socket
import tkinter as tk
from tkinter import scrolledtext, ttk
import threading

class SocketServer:
    def __init__(self, root):
        self.root = root
        self.root.title("Socket 服务端")
        self.root.geometry("500x400")
        
        # 设置界面
        self.setup_ui()
        
        # 初始化服务器
        self.server_socket = None
        self.is_running = False
        
        # 启动服务器按钮
        self.start_button.config(command=self.start_server)
        self.stop_button.config(command=self.stop_server, state=tk.DISABLED)
    
    def setup_ui(self):
        # 创建顶部控制区
        control_frame = ttk.Frame(self.root, padding="10")
        control_frame.pack(fill=tk.X)
        
        ttk.Label(control_frame, text="主机:").pack(side=tk.LEFT, padx=5)
        self.host_entry = ttk.Entry(control_frame, width=20)
        self.host_entry.pack(side=tk.LEFT, padx=5)
        self.host_entry.insert(0, socket.gethostname())
        
        ttk.Label(control_frame, text="端口:").pack(side=tk.LEFT, padx=5)
        self.port_entry = ttk.Entry(control_frame, width=10)
        self.port_entry.pack(side=tk.LEFT, padx=5)
        self.port_entry.insert(0, "12345")
        
        self.start_button = ttk.Button(control_frame, text="启动服务器")
        self.start_button.pack(side=tk.LEFT, padx=5)
        
        self.stop_button = ttk.Button(control_frame, text="停止服务器")
        self.stop_button.pack(side=tk.LEFT, padx=5)
        
        # 创建消息显示区
        ttk.Label(self.root, text="接收消息:").pack(anchor=tk.W, padx=10)
        self.message_area = scrolledtext.ScrolledText(self.root, wrap=tk.WORD, width=60, height=15)
        self.message_area.pack(padx=10, pady=5, fill=tk.BOTH, expand=True)
        self.message_area.config(state=tk.DISABLED)
    
    def log_message(self, message):
        """在消息区域显示信息"""
        self.message_area.config(state=tk.NORMAL)
        self.message_area.insert(tk.END, message + "\n")
        self.message_area.see(tk.END)  # 滚动到最后
        self.message_area.config(state=tk.DISABLED)
    
    def start_server(self):
        """启动服务器"""
        if self.is_running:
            self.log_message("服务器已在运行中")
            return
        
        try:
            host = self.host_entry.get()
            port = int(self.port_entry.get())
            
            self.server_socket = socket.socket()
            self.server_socket.bind((host, port))
            self.server_socket.listen(5)
            self.is_running = True
            
            self.log_message(f"服务器已启动，监听 {host}:{port}")
            self.start_button.config(state=tk.DISABLED)
            self.stop_button.config(state=tk.NORMAL)
            
            # 在新线程中接受连接，避免阻塞UI
            threading.Thread(target=self.accept_connections, daemon=True).start()
            
        except Exception as e:
            self.log_message(f"启动服务器失败: {str(e)}")
    
    def stop_server(self):
        """停止服务器"""
        if not self.is_running:
            return
            
        self.is_running = False
        if self.server_socket:
            try:
                self.server_socket.close()
            except Exception as e:
                self.log_message(f"关闭服务器时出错: {str(e)}")
        
        self.log_message("服务器已停止")
        self.start_button.config(state=tk.NORMAL)
        self.stop_button.config(state=tk.DISABLED)
    
    def accept_connections(self):
        """接受客户端连接"""
        while self.is_running:
            try:
                client_socket, addr = self.server_socket.accept()
                self.log_message(f"新连接: {addr}")
                
                # 处理客户端消息
                threading.Thread(target=self.handle_client, args=(client_socket, addr), daemon=True).start()
                
            except Exception as e:
                if self.is_running:  # 如果不是主动停止的，才显示错误
                    self.log_message(f"接受连接时出错: {str(e)}")
                break
    
    def handle_client(self, client_socket, addr):
        """处理客户端消息"""
        try:
            # 接收客户端消息
            data = client_socket.recv(1024).decode('utf-8')
            if data:
                self.log_message(f"从 {addr} 收到: {data}")
                
                # 可以在这里添加回复逻辑
                response = "消息已收到: " + data
                client_socket.send(response.encode('utf-8'))
                
        except Exception as e:
            self.log_message(f"处理客户端 {addr} 时出错: {str(e)}")
        finally:
            client_socket.close()
            self.log_message(f"与 {addr} 的连接已关闭")

if __name__ == "__main__":
    root = tk.Tk()
    app = SocketServer(root)
    root.mainloop()






















# import socket

# s= socket.socket()
# host = socket.gethostname()
# port = 12345
# s.bind((host, port))

# s.listen(5)
# while True:
#     c,addr= s.accept()
#     print('链接地址',addr)
#     msg = input("请输入消息：")
#     c.send(msg.encode('utf-8'))
#     c.close()
    